/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * mainWindow.java
 *
 * Created on 23/03/2009, 22:41:51
 */

package NewGUI;

import java.awt.*;

import javax.imageio.ImageIO;
import javax.swing.*;
import scrabbleMain.Board;
import scrabbleMain.GameGui;
import scrabbleMain.GameLogic;
import scrabbleMain.Player;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Color;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.Transparency;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.PixelGrabber;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Random;
import javax.swing.DesktopManager;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JPanel;

import Gui.MainWindow1.resultAddLetter;
import Gui.MainWindow1.resultSwapLetter;
import resources.resConfig;
import resources.Letter2.letter2Config;
import resources.Letters.lettersConfig;
/**
 * 
 * @author Roy
 */
public class MainWindow1 extends javax.swing.JFrame {
	
	/** Creates new form mainWindow */
	public MainWindow1() {
		GameGui.UploadrecordList('b');
		GameGui.UploadrecordList('a');
		initComponents();
		GameGui.getG().mainWindow = this;
	}


	// general return value parameter. will be used in file choosers
	private int returnVal = 0;
	public boolean changeLetterFlag = false; // a flag that is set once the
												// user press the button change
												// letter
	public boolean addWordFlag          = false; // set when the user press addWord
	public boolean advancedLetterPlaced = false; // set after the user placed the letter in advanced mode
	public boolean moveProgress         = false; // a flag that is true once a 'move'
											// is in progress
	public resultAddLetter resultAdd = null; // a result for the logic of the
												// addWord operation
	public resultSwapLetter resultSwap = null; // a result for the logic of the
												// swapWord operation
	// public Board board = new Board(15, 15, ""); //the board;
	public Player player = new Player(""); // the current player

	private static boolean isSaved = false;
    private static int TableColor = 0;
    private static int LetterColor = 0;
	
	/** Creates new form mainWindow */

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed" desc="Generated
	// Code">//GEN-BEGIN:initComponents
	private void initComponents() {

		helpPage = new javax.swing.JDialog();
		okHelpButton = new javax.swing.JButton();
		helpText1 = new javax.swing.JScrollPane();
		helpjTextPane1 = new javax.swing.JTextPane();
		helpText2 = new javax.swing.JScrollPane();
		helpjTextPane2 = new javax.swing.JTextPane();
		bestResultsPageBasic = new javax.swing.JDialog();
		okBestBasicButton = new javax.swing.JButton();
		bestBasicjScrollPane = new javax.swing.JScrollPane();
		bestBasicjTextPane = new javax.swing.JTextPane();
		bestResultsPageAdvanced = new javax.swing.JDialog();
		okBestAdvancedButton = new javax.swing.JButton();
		bestAdvancedjScrollPane = new javax.swing.JScrollPane();
		bestAdvancedjTextPane = new javax.swing.JTextPane();
		addWordToBoard = new javax.swing.JButton();
		currentPlayer = new javax.swing.JLabel();
		letterSack = new javax.swing.JLabel();
		scoreBoard = new javax.swing.JTextPane();
		changeLetter = new javax.swing.JButton();
		doneButton = new javax.swing.JButton();
		playStatus = new javax.swing.JTextPane();
		gameBoard = new DrawPanel();
		jMenuBar1 = new javax.swing.JMenuBar();
		gameMenu = new javax.swing.JMenu();
		newGameMenuItem = new javax.swing.JMenuItem();
		saveMenuItem = new javax.swing.JMenuItem();
		loadMenuItem = new javax.swing.JMenuItem();
		gameMenuSeparator = new javax.swing.JSeparator();
		exitMenuItem = new javax.swing.JMenuItem();
		viewMenu = new javax.swing.JMenu();
        viewComponent =new javax.swing.JDialog();
        viewComponent2 =new javax.swing.JDialog();
		bestResults = new javax.swing.JMenu();
		bestBasic = new javax.swing.JMenuItem();
		bestAdvanced = new javax.swing.JMenuItem();
		helpMenu1 = new javax.swing.JMenu();
		helpMenuItem1 = new javax.swing.JMenuItem();
		helpMenuSeparator1 = new javax.swing.JSeparator();
		aboutUsMenuItem1 = new javax.swing.JMenuItem();
        viewLetterT = new javax.swing.JLabel();
        viewWindowT = new javax.swing.JLabel();
        BlueLetter = new javax.swing.JRadioButton();
        redLetter= new javax.swing.JRadioButton();
        letterOk = new javax.swing.JButton();
        viewMenuItem= new javax.swing.JMenuItem();
        viewMenuItem2= new javax.swing.JMenuItem();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jRadioButton1 = new javax.swing.JRadioButton();
        jRadioButton2 = new javax.swing.JRadioButton();
        jButton1 = new javax.swing.JButton();
        jRadioButton3 = new javax.swing.JRadioButton();
        AboutUsOkButton = new javax.swing.JButton();
        AboutUsjScrollPane1 = new javax.swing.JScrollPane();
        AboutUsTextPane1 = new javax.swing.JTextPane();
        AboutUsDialog = new javax.swing.JDialog();
       
        
        AboutUsOkButton.setText("Ok");
        AboutUsOkButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AboutUsOkButtonEvent(evt);
            }
        });

        AboutUsTextPane1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        AboutUsTextPane1.setText("The creators of this game are:\n                                                 Eviatar\n                                                 Roy\n                                                  Polina\n                                                  Alex\n                                                  Erez\n                                                  Andreea\nAll rights are reserved \n\nFor suggestions or complains please contact us at:\n     ");
        AboutUsjScrollPane1.setViewportView(AboutUsTextPane1);
        
     

        javax.swing.GroupLayout AboutUslayout = new javax.swing.GroupLayout(AboutUsDialog.getContentPane());
        AboutUsDialog.getContentPane().setLayout(AboutUslayout);
        AboutUslayout.setHorizontalGroup(
            AboutUslayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(AboutUslayout.createSequentialGroup()
                .addGroup(AboutUslayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(AboutUslayout.createSequentialGroup()
                        .addGap(45, 45, 45)
                        .addComponent(AboutUsjScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 324, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(AboutUslayout.createSequentialGroup()
                        .addGap(171, 171, 171)
                        .addComponent(AboutUsOkButton, javax.swing.GroupLayout.PREFERRED_SIZE,90, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(82, Short.MAX_VALUE))
        );
        AboutUslayout.setVerticalGroup(
            AboutUslayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(AboutUslayout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addComponent(AboutUsjScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(AboutUsOkButton, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(19, 19, 19))
        );


         jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel1.setText("Select the table color");

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel2.setText("Table View options");

        jRadioButton1.setSelected(true);
        jRadioButton1.setText("White");
        jRadioButton1.setToolTipText("The table will be white");
        jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                WhiteTableHandler(evt);
            }
        });

        jRadioButton2.setText("Redish");
        jRadioButton2.setToolTipText("The table will be redish");
        jRadioButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RedTableHandler(evt);
            }
        });

        jButton1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jButton1.setText("Ok");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                OkTableViewActionPerformed(evt);
            }
        });

        jRadioButton3.setText("Blue");
        jRadioButton3.setToolTipText("The table will be with a tint of blue");
          jRadioButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BlueTableHandler(evt);
            }
        });


        javax.swing.GroupLayout TableViewlayout = new javax.swing.GroupLayout(viewComponent2.getContentPane());
       viewComponent2. getContentPane().setLayout(TableViewlayout);
        TableViewlayout.setHorizontalGroup(
            TableViewlayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(TableViewlayout.createSequentialGroup()
                .addGap(46, 46, 46)
                .addGroup(TableViewlayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(TableViewlayout.createSequentialGroup()
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .addGroup(TableViewlayout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 53, Short.MAX_VALUE)
                        .addGroup(TableViewlayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jRadioButton1)
                            .addComponent(jRadioButton3)
                            .addComponent(jRadioButton2))
                        .addGap(168, 168, 168))))
            .addGroup(TableViewlayout.createSequentialGroup()
                .addGap(148, 148, 148)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(205, Short.MAX_VALUE))
        );
        TableViewlayout.setVerticalGroup(
            TableViewlayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(TableViewlayout.createSequentialGroup()
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(29, 29, 29)
                .addGroup(TableViewlayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jRadioButton1)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jRadioButton2)
                .addGap(3, 3, 3)
                .addComponent(jRadioButton3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

      
        viewLetterT.setFont(new java.awt.Font("Tahoma", 0, 14));
        viewLetterT.setText("Select the letters color");

        viewWindowT .setFont(new java.awt.Font("Tahoma", 1, 14));
        viewWindowT .setText("Table View options");

         BlueLetter.setSelected(true);
         BlueLetter.setText("Blue ");
         BlueLetter.setToolTipText("The letters become blue");
         BlueLetter.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBlueColorRadioButtonActionPerformed(evt);
            }
        });

      redLetter.setText("Red");
      redLetter.setToolTipText("The letters become red");
      redLetter.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRedColorRadioButtonActionPerformed(evt);
            }
        });

        letterOk.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        letterOk.setText("Ok");
        letterOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                OkViewActionPerformed(evt);
            }
        });



		helpPage.setMinimumSize(new java.awt.Dimension(645, 566));
		helpPage.setResizable(false);

        viewComponent.setMinimumSize(new java.awt.Dimension(325,255));
        viewComponent.setResizable(false);

        viewComponent2.setMinimumSize(new java.awt.Dimension(325,255));
        viewComponent2.setResizable(false);
        
        AboutUsDialog.setMinimumSize(new java.awt.Dimension(425,370));
        AboutUsDialog.setResizable(false);
        AboutUsTextPane1.setEditable(false);
        
        AboutUsDialog.add(AboutUsjScrollPane1);
  
		okHelpButton.setFont(new java.awt.Font("Tahoma", 0, 36));
		okHelpButton.setText("Ok");
		okHelpButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				okHelpButtonActionPerformed(evt);
			}
		});

		helpjTextPane1.setBackground(javax.swing.UIManager.getDefaults()
				.getColor("Button.background"));
		helpjTextPane1.setContentType("rich text");
		helpjTextPane1.setEditable(false);
		helpjTextPane1.setText(GameGui.parseFileToString("help_file1.txt"));
		helpjTextPane1.setMinimumSize(new java.awt.Dimension(408, 342));
		helpText1.setViewportView(helpjTextPane1);

		helpjTextPane2.setBackground(javax.swing.UIManager.getDefaults()
				.getColor("Button.background"));
		helpjTextPane2.setContentType("rich text");
		helpjTextPane2.setEditable(false);
		helpjTextPane2.setText(GameGui.parseFileToString("help_file2.txt"));
		helpText2.setViewportView(helpjTextPane2);

             javax.swing.GroupLayout viewlayout = new javax.swing.GroupLayout(
                     viewComponent.getContentPane());
       viewComponent. getContentPane().setLayout(viewlayout);
      viewlayout.setHorizontalGroup(
            viewlayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(viewlayout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addGroup(viewlayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(viewlayout.createSequentialGroup()
                        .addComponent(viewWindowT, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .addGroup(viewlayout.createSequentialGroup()
                        .addGroup(viewlayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(letterOk, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(viewlayout.createSequentialGroup()
                                .addComponent(viewLetterT)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 53, Short.MAX_VALUE)
                                .addGroup(viewlayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(redLetter)
                                    .addComponent( BlueLetter))))
                        .addGap(168, 168, 168))))
        );
       viewlayout.setVerticalGroup(
            viewlayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(viewlayout.createSequentialGroup()
                .addComponent(viewWindowT, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(29, 29, 29)
                .addGroup(viewlayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent( BlueLetter)
                    .addComponent(viewLetterT))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(redLetter)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 65, Short.MAX_VALUE)
                .addComponent(letterOk, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
		javax.swing.GroupLayout helpPageLayout = new javax.swing.GroupLayout(
				helpPage.getContentPane());
		helpPage.getContentPane().setLayout(helpPageLayout);
		helpPageLayout
				.setHorizontalGroup(helpPageLayout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								helpPageLayout
										.createSequentialGroup()
										.addContainerGap()
										.addComponent(
												helpText1,
												javax.swing.GroupLayout.PREFERRED_SIZE,
												306,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
										.addComponent(
												helpText2,
												javax.swing.GroupLayout.DEFAULT_SIZE,
												305, Short.MAX_VALUE)
										.addContainerGap())
						.addGroup(
								javax.swing.GroupLayout.Alignment.TRAILING,
								helpPageLayout
										.createSequentialGroup()
										.addContainerGap(225, Short.MAX_VALUE)
										.addComponent(
												okHelpButton,
												javax.swing.GroupLayout.PREFERRED_SIZE,
												200,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addGap(216, 216, 216)));
		helpPageLayout
				.setVerticalGroup(helpPageLayout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								helpPageLayout
										.createSequentialGroup()
										.addContainerGap()
										.addGroup(
												helpPageLayout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.LEADING,
																false)
														.addComponent(helpText2)
														.addComponent(helpText1))
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
										.addComponent(okHelpButton)
										.addContainerGap(
												javax.swing.GroupLayout.DEFAULT_SIZE,
												Short.MAX_VALUE)));

		bestResultsPageBasic.setMinimumSize(new java.awt.Dimension(645, 566));

		okBestBasicButton.setFont(new java.awt.Font("Tahoma", 0, 36));
		okBestBasicButton.setText("Ok");
		okBestBasicButton
				.addActionListener(new java.awt.event.ActionListener() {
					public void actionPerformed(java.awt.event.ActionEvent evt) {
						okBestBasicButtonActionPerformed(evt);
					}
				});

		bestBasicjTextPane.setBackground(javax.swing.UIManager.getDefaults()
				.getColor("Button.background"));
		bestBasicjTextPane.setEditable(false);
		
		bestBasicjTextPane
				.setText(GameGui.printRecordListToLabel('b'));
		bestBasicjTextPane.setAutoscrolls(false);
		bestBasicjScrollPane.setViewportView(bestBasicjTextPane);

		javax.swing.GroupLayout bestResultsPageBasicLayout = new javax.swing.GroupLayout(
				bestResultsPageBasic.getContentPane());
		bestResultsPageBasic.getContentPane().setLayout(
				bestResultsPageBasicLayout);
		bestResultsPageBasicLayout
				.setHorizontalGroup(bestResultsPageBasicLayout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								bestResultsPageBasicLayout
										.createSequentialGroup()
										.addGroup(
												bestResultsPageBasicLayout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.LEADING)
														.addGroup(
																bestResultsPageBasicLayout
																		.createSequentialGroup()
																		.addGap(
																				221,
																				221,
																				221)
																		.addComponent(
																				okBestBasicButton,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				200,
																				javax.swing.GroupLayout.PREFERRED_SIZE))
														.addGroup(
																bestResultsPageBasicLayout
																		.createSequentialGroup()
																		.addGap(
																				63,
																				63,
																				63)
																		.addComponent(
																				bestBasicjScrollPane,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				522,
																				javax.swing.GroupLayout.PREFERRED_SIZE)))
										.addContainerGap(60, Short.MAX_VALUE)));
		bestResultsPageBasicLayout
				.setVerticalGroup(bestResultsPageBasicLayout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								javax.swing.GroupLayout.Alignment.TRAILING,
								bestResultsPageBasicLayout
										.createSequentialGroup()
										.addContainerGap()
										.addComponent(
												bestBasicjScrollPane,
												javax.swing.GroupLayout.PREFERRED_SIZE,
												429,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED,
												43, Short.MAX_VALUE)
										.addComponent(
												okBestBasicButton,
												javax.swing.GroupLayout.PREFERRED_SIZE,
												72,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addContainerGap()));

		bestResultsPageAdvanced
				.setMinimumSize(new java.awt.Dimension(645, 566));

		okBestAdvancedButton.setFont(new java.awt.Font("Tahoma", 0, 36));
		okBestAdvancedButton.setText("Ok");
		okBestAdvancedButton
				.addActionListener(new java.awt.event.ActionListener() {
					public void actionPerformed(java.awt.event.ActionEvent evt) {
						okBestAdvancedButtonActionPerformed(evt);
					}
				});

		bestAdvancedjTextPane.setBackground(javax.swing.UIManager.getDefaults()
				.getColor("Button.background"));
		bestAdvancedjTextPane.setEditable(false);
		bestAdvancedjTextPane.setText(GameGui.printRecordListToLabel('a'));
		bestAdvancedjTextPane.setAutoscrolls(false);
		bestAdvancedjScrollPane.setViewportView(bestAdvancedjTextPane);

		javax.swing.GroupLayout bestResultsPageAdvancedLayout = new javax.swing.GroupLayout(
				bestResultsPageAdvanced.getContentPane());
		bestResultsPageAdvanced.getContentPane().setLayout(
				bestResultsPageAdvancedLayout);
		bestResultsPageAdvancedLayout
				.setHorizontalGroup(bestResultsPageAdvancedLayout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								bestResultsPageAdvancedLayout
										.createSequentialGroup()
										.addGroup(
												bestResultsPageAdvancedLayout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.LEADING)
														.addGroup(
																bestResultsPageAdvancedLayout
																		.createSequentialGroup()
																		.addGap(
																				221,
																				221,
																				221)
																		.addComponent(
																				okBestAdvancedButton,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				200,
																				javax.swing.GroupLayout.PREFERRED_SIZE))
														.addGroup(
																bestResultsPageAdvancedLayout
																		.createSequentialGroup()
																		.addGap(
																				47,
																				47,
																				47)
																		.addComponent(
																				bestAdvancedjScrollPane,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				522,
																				javax.swing.GroupLayout.PREFERRED_SIZE)))
										.addContainerGap(76, Short.MAX_VALUE)));
		bestResultsPageAdvancedLayout
				.setVerticalGroup(bestResultsPageAdvancedLayout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								javax.swing.GroupLayout.Alignment.TRAILING,
								bestResultsPageAdvancedLayout
										.createSequentialGroup()
										.addContainerGap(36, Short.MAX_VALUE)
										.addComponent(
												bestAdvancedjScrollPane,
												javax.swing.GroupLayout.PREFERRED_SIZE,
												429,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addGap(18, 18, 18)
										.addComponent(
												okBestAdvancedButton,
												javax.swing.GroupLayout.PREFERRED_SIZE,
												72,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addContainerGap()));

		setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
		setResizable(false);
		addWindowListener(new java.awt.event.WindowAdapter() {
			public void windowClosing(java.awt.event.WindowEvent evt) {
				formWindowClosing(evt);
			}
		});

		addWordToBoard.setText("Add Word");
		addWordToBoard.setToolTipText("Add a new word to board");
		addWordToBoard.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				addWordToBoardActionPerformed(evt);
			}
		});

		currentPlayer.setFont(new java.awt.Font("Tahoma", 1, 12));
		currentPlayer.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
		currentPlayer.setText("Now Playing: " + GameGui.getG().getCurrentPlayerName());
		
		
		updateLetterSackBox();
		
		letterSack.setBorder(javax.swing.BorderFactory.createTitledBorder(null,
				"Letter Sack",
				javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
				javax.swing.border.TitledBorder.DEFAULT_POSITION,
				new java.awt.Font("Tahoma", 1, 12))); // NOI18N

		scoreBoard.setBorder(javax.swing.BorderFactory.createTitledBorder(null,
				"Score Board",
				javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
				javax.swing.border.TitledBorder.DEFAULT_POSITION,
				new java.awt.Font("Tahoma", 1, 12))); // NOI18N
		scoreBoard.setEditable(false);
		scoreBoard.setBackground(new java.awt.Color(204, 204, 255));
		scoreBoard.setFont(new java.awt.Font("Arial Narrow", 3, 14));
		scoreBoard.setBorder(javax.swing.BorderFactory.createTitledBorder
				(new javax.swing.border.LineBorder
						(new java.awt.Color(102, 0, 0), 2, true), "Score Board", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("David", 3, 24), new java.awt.Color(204, 0, 0)));
		
		updateScoreBoard();

		changeLetter.setText("Change Letter");
		changeLetter.setToolTipText("Replace a letter with a new letter");
		changeLetter
				.addContainerListener(new java.awt.event.ContainerAdapter() {
					public void componentAdded(java.awt.event.ContainerEvent evt) {
						changeLetterComponentAdded(evt);
					}

					public void componentRemoved(
							java.awt.event.ContainerEvent evt) {
						changeLetterComponentRemoved(evt);
					}
				});
		changeLetter.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				changeLetterActionPerformed(evt);
			}
		});

		doneButton.setText("Done!");
		doneButton.setToolTipText("I'm done playing this turn");
		doneButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				doneButtonActionPerformed(evt);
			}
		});


//		playStatus.setText("play status will be presented here");
		playStatus.setBorder(javax.swing.BorderFactory.createTitledBorder(
				new javax.swing.border.LineBorder(new java.awt.Color
						(102, 0, 0), 2, true), "PlayStatus", 
						javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, 
						javax.swing.border.TitledBorder.DEFAULT_POSITION, 
						new java.awt.Font("David", 3, 24), new java.awt.Color
						(204, 0, 0))); // NOI18N
		playStatus.setEditable(false);
		playStatus.setFont(new java.awt.Font("Arial Narrow", 3, 15)); // NOI18N
		playStatus.setForeground(new java.awt.Color(255, 0, 0));
		playStatus.setBackground(new java.awt.Color(204, 204, 255));
		
		
		gameMenu.setText("Game");
		gameMenu.setToolTipText("Game options");
		gameMenu.addKeyListener(new java.awt.event.KeyAdapter() {
			public void keyPressed(java.awt.event.KeyEvent evt) {
				gameMenuKeyPressed(evt);
			}
		});

		newGameMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
				java.awt.event.KeyEvent.VK_N,
				java.awt.event.InputEvent.CTRL_MASK));
		newGameMenuItem.setText("New Game");
		newGameMenuItem.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				newGameMenuItemActionPerformed(evt);
			}
		});
		newGameMenuItem.addKeyListener(new java.awt.event.KeyAdapter() {
			public void keyPressed(java.awt.event.KeyEvent evt) {
				newGameMenuItemKeyPressed(evt);
			}
		});
		gameMenu.add(newGameMenuItem);

		saveMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
				java.awt.event.KeyEvent.VK_S,
				java.awt.event.InputEvent.CTRL_MASK));
		saveMenuItem.setText("Save");
		saveMenuItem.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				saveMenuItemMouseClicked(evt);
			}
		});
		saveMenuItem.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				saveMenuItemActionPerformed(evt);
			}
		});
		saveMenuItem.addKeyListener(new java.awt.event.KeyAdapter() {
			public void keyPressed(java.awt.event.KeyEvent evt) {
				saveMenuItemKeyPressed(evt);
			}
		});
		gameMenu.add(saveMenuItem);

		loadMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
				java.awt.event.KeyEvent.VK_L,
				java.awt.event.InputEvent.CTRL_MASK));
		loadMenuItem.setText("Load");
		loadMenuItem.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				loadMenuItemActionPerformed(evt);
			}
		});
		loadMenuItem.addKeyListener(new java.awt.event.KeyAdapter() {
			public void keyPressed(java.awt.event.KeyEvent evt) {
				loadMenuItemKeyPressed(evt);
			}
		});
		gameMenu.add(loadMenuItem);
		gameMenu.add(gameMenuSeparator);

		exitMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
				java.awt.event.KeyEvent.VK_Q,
				java.awt.event.InputEvent.CTRL_MASK));
		exitMenuItem.setText("Exit");
		exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				exitMenuItemActionPerformed(evt);
			}
		});
		exitMenuItem.addKeyListener(new java.awt.event.KeyAdapter() {
			public void keyPressed(java.awt.event.KeyEvent evt) {
				exitMenuItemKeyPressed(evt);
			}
		});
		gameMenu.add(exitMenuItem);

		jMenuBar1.add(gameMenu);

		viewMenu.setText("View");
		viewMenu.setToolTipText("Graphics options");
		jMenuBar1.add(viewMenu);
        viewMenuItem.setText("Letters View");
        viewMenuItem2.setText("Table View");


	
        viewMenuItem.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				viewmenuActionPerformed(evt);
			}
        });

        viewMenuItem.addKeyListener(new java.awt.event.KeyAdapter(){
            	public void keyPressed(java.awt.event.KeyEvent evt) {
				viewmenuKeyPressed(evt);
			}
        });
          viewMenuItem2.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				viewmenu2ActionPerformed(evt);
			}
        });

        viewMenuItem2.addKeyListener(new java.awt.event.KeyAdapter(){
            	public void keyPressed(java.awt.event.KeyEvent evt) {
				viewmenu2KeyPressed(evt);
			}
        });
        aboutUsMenuItem1.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				AboutUsActionPerformed(evt);
			}
        });

        aboutUsMenuItem1.addKeyListener(new java.awt.event.KeyAdapter(){
            	public void keyPressed(java.awt.event.KeyEvent evt) {
				AboutUsKeyPressed(evt);
			}

        });

        viewMenu.add(viewMenuItem2);

        viewMenu.add(viewMenuItem);

		bestResults.setText("Hall Of Fame");
		bestResults.setToolTipText("View Best results");

		bestBasic.setText("Best Results - Basic Game");
		bestBasic.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				bestBasicActionPerformed(evt);
			}
		});
		bestResults.add(bestBasic);

		bestAdvanced.setText("Best Results - Advanced Game");
		bestAdvanced.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				bestAdvancedActionPerformed(evt);
			}
		});
		bestResults.add(bestAdvanced);

		jMenuBar1.add(bestResults);

		helpMenu1.setText("Help");
		helpMenu1.setToolTipText("Help me...");

		helpMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(
				java.awt.event.KeyEvent.VK_H,
				java.awt.event.InputEvent.CTRL_MASK));
		helpMenuItem1.setText("Help");
		helpMenuItem1.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				helpMenuItem1ActionPerformed(evt);
			}
		});
		helpMenuItem1.addKeyListener(new java.awt.event.KeyAdapter() {
			public void keyPressed(java.awt.event.KeyEvent evt) {
				helpMenuItem1KeyPressed(evt);
			}
		});
		helpMenu1.add(helpMenuItem1);
		helpMenu1.add(helpMenuSeparator1);

		aboutUsMenuItem1.setText("About Us");
		aboutUsMenuItem1.setToolTipText("Who are we?");
		helpMenu1.add(aboutUsMenuItem1);

		jMenuBar1.add(helpMenu1);

		setJMenuBar(jMenuBar1);

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
				getContentPane());
		getContentPane().setLayout(layout);
		layout
				.setHorizontalGroup(layout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								layout
										.createSequentialGroup()
										.addContainerGap()
										.addGroup(
												layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.LEADING)
														.addGroup(
																layout
																		.createSequentialGroup()
																		.addGroup(
																				layout
																						.createParallelGroup(
																								javax.swing.GroupLayout.Alignment.LEADING,
																								false)
																						.addComponent(
																								scoreBoard,
																								javax.swing.GroupLayout.Alignment.TRAILING,
																								javax.swing.GroupLayout.DEFAULT_SIZE,
																								143,
																								Short.MAX_VALUE)
																						.addComponent(
																								playStatus,
																								javax.swing.GroupLayout.Alignment.TRAILING,
																								javax.swing.GroupLayout.PREFERRED_SIZE,
																								143,
																								Short.MAX_VALUE)
																						.addGroup(
																								layout
																										.createSequentialGroup()
																										.addGap(
																												15,
																												15,
																												15)
																										.addComponent(
																												doneButton,
																												javax.swing.GroupLayout.PREFERRED_SIZE,
																												114,
																												javax.swing.GroupLayout.PREFERRED_SIZE)))
																		.addGap(
																				10,
																				10,
																				10))
														.addGroup(
																layout
																		.createSequentialGroup()
																		.addComponent(
																				letterSack,
																				javax.swing.GroupLayout.DEFAULT_SIZE,
																				188,
																				Short.MAX_VALUE)
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
										.addGroup(
												layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.LEADING)
														.addGroup(
																layout
																		.createSequentialGroup()
																		.addGap(
																				34,
																				34,
																				34)
																		.addGroup(
																				layout
																						.createParallelGroup(
																								javax.swing.GroupLayout.Alignment.LEADING,
																								false)
																						.addGroup(
																								layout
																										.createSequentialGroup()
																										.addComponent(
																												changeLetter,
																												javax.swing.GroupLayout.PREFERRED_SIZE,
																												121,
																												javax.swing.GroupLayout.PREFERRED_SIZE)
																										.addGap(
																												163,
																												163,
																												163)
																										.addComponent(
																												addWordToBoard,
																												javax.swing.GroupLayout.PREFERRED_SIZE,
																												127,
																												javax.swing.GroupLayout.PREFERRED_SIZE))
																						.addComponent(
																								currentPlayer,
																								javax.swing.GroupLayout.DEFAULT_SIZE,
																								javax.swing.GroupLayout.DEFAULT_SIZE,
																								Short.MAX_VALUE)))
														.addGroup(
																layout
																		.createSequentialGroup()
																		.addGap(
																				17,
																				17,
																				17)
																		.addComponent(
																				gameBoard,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				480,
																				javax.swing.GroupLayout.PREFERRED_SIZE)))
										.addContainerGap(
												javax.swing.GroupLayout.DEFAULT_SIZE,
												Short.MAX_VALUE)));
		layout
				.setVerticalGroup(layout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								layout
										.createSequentialGroup()
										.addGroup(
												layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.LEADING,
																false)
														.addGroup(
																layout
																		.createSequentialGroup()
																		.addContainerGap()
																		.addComponent(
																				playStatus,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				119,
																				javax.swing.GroupLayout.PREFERRED_SIZE)
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
																		.addComponent(
																				doneButton,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				36,
																				javax.swing.GroupLayout.PREFERRED_SIZE)
																		.addGap(
																				18,
																				18,
																				18)
																		.addComponent(
																				scoreBoard,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				332,
																				javax.swing.GroupLayout.PREFERRED_SIZE))
														.addGroup(
																layout
																		.createSequentialGroup()
																		.addGap(
																				19,
																				19,
																				19)
																		.addComponent(
																				gameBoard,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				480,
																				Short.MAX_VALUE)))
										.addGroup(
												layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.LEADING)
														.addGroup(
																layout
																		.createSequentialGroup()
																		.addGap(
																				81,
																				81,
																				81)
																		.addGroup(
																				layout
																						.createParallelGroup(
																								javax.swing.GroupLayout.Alignment.BASELINE)
																						.addComponent(
																								changeLetter,
																								javax.swing.GroupLayout.PREFERRED_SIZE,
																								55,
																								javax.swing.GroupLayout.PREFERRED_SIZE)
																						.addComponent(
																								addWordToBoard,
																								javax.swing.GroupLayout.PREFERRED_SIZE,
																								54,
																								javax.swing.GroupLayout.PREFERRED_SIZE))
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																		.addComponent(
																				currentPlayer,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				29,
																				javax.swing.GroupLayout.PREFERRED_SIZE))
														.addGroup(
																layout
																		.createSequentialGroup()
																		.addGap(
																				28,
																				28,
																				28)
																		.addComponent(
																				letterSack,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				128,
																				javax.swing.GroupLayout.PREFERRED_SIZE)))
										.addGap(25, 25, 25)));

		pack();
	}// </editor-fold>//GEN-END:initComponents

	private void updateLetterSackBox() {
		letterSack.setText("Number of letters Left: " + GameGui.getG().getLettersSet().getLetterSetSize());
	}

	private void saveMenuItemMouseClicked(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_saveMenuItemMouseClicked
		// TODO add your handling code here:
	}// GEN-LAST:event_saveMenuItemMouseClicked

	private void loadMenuItemActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_loadMenuItemActionPerformed
		if (!isSaved) //check if saved
		{
			SaveBeforeExitScreen.startSaveBeforeExitScreen(MainWindow1.this, "load");
		}
		else
		{
			gameFileChooser.startLoadChooser(MainWindow1.this);
		}

	}// GEN-LAST:event_loadMenuItemActionPerformed

	private void saveMenuItemActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_saveMenuItemActionPerformed
		gameFileChooser.startSaveChooser(MainWindow1.this);
	}// GEN-LAST:event_saveMenuItemActionPerformed

	private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_exitMenuItemActionPerformed
		
		if (!isSaved) //check if saved
		{
			SaveBeforeExitScreen.startSaveBeforeExitScreen(MainWindow1.this, "exit");
		}
		else
		{
			ExitScreen.startExitScreen(MainWindow1.this);
		}
		
	}// GEN-LAST:event_exitMenuItemActionPerformed

	/*
	 * This is the event from done button. 
	 */
	private void doneButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_doneButtonActionPerformed
		//current player is human
		if (GameGui.getG().getPlayerList().get(GameGui.getG().getTurnInd()).isAuto() == false) {
			//player pressed done before he pressed "change letters" or "add word"
			if ((changeLetterFlag == false) && (addWordFlag == false)){
				setPlayStatusText("Choose add word or change letter");
				return;
			}
			if (changeLetterFlag == true) {
				GameGui.moveToNextPlayer();
				setPlayStatusText("");
			}
			else if (addWordFlag == true) {
				GameGui.placeWordBasic();
				GameGui.moveToNextPlayer();
//				setPlayStatusText("");
			}
		}
		//if the current player is automatic
		else {
			GameGui.placeAutoWord();
			GameGui.moveToNextPlayer();
		}
		
		gameBoard.repaint();

		MainWindow1.setSaved(false);
		
		//set the board accordingly if the current player is auto or human
		if (GameGui.getG().getPlayerList().get(GameGui.getG().getTurnInd()).isAuto() == true) {
			changeLetter.setEnabled(false);
			addWordToBoard.setEnabled(false);
//			setPlayStatusText("The current turn is an auto player turn, press Done for him to make his move");
		}
		else {
			changeLetter.setEnabled(true);
			addWordToBoard.setEnabled(true);
		}
		
		changeLetterFlag = false;
		addWordFlag      = false;
		
		//check if game finished
		if (GameGui.getG().getLettersSet().getLetterSetSize() == 0) {
			changeLetter.setEnabled(false);
			addWordToBoard.setEnabled(false);
			doneButton.setEnabled(false);
			setPlayStatusText("letters are finished, Game is finished");
			updateScoreBoard();
			return;
		}
		
		advancedLetterPlaced = false;

		currentPlayer.setText("Now Playing: " + GameGui.getG().getCurrentPlayerName());
		updateLetterSackBox();
		updateScoreBoard();
		

	}// GEN-LAST:event_doneButtonActionPerformed



	private void newGameMenuItemActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_newGameMenuItemActionPerformed
		if (!isSaved) //check if saved
		{
			SaveBeforeExitScreen.startSaveBeforeExitScreen(MainWindow1.this, "new");
		}
		else
		{
			// Start a new game from menu.
			NewGameDialog.startNewGame(MainWindow1.this);
		}
	}// GEN-LAST:event_newGameMenuItemActionPerformed

	private void gameMenuKeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_gameMenuKeyPressed
		// TODO add your handling code here:
	}// GEN-LAST:event_gameMenuKeyPressed

	private void newGameMenuItemKeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_newGameMenuItemKeyPressed
		if (!isSaved) //check if saved
		{
			SaveBeforeExitScreen.startSaveBeforeExitScreen(MainWindow1.this, "new");
		}
		else
		{
			// Start a new game from menu.
			NewGameDialog.startNewGame(MainWindow1.this);
		}
	}// GEN-LAST:event_newGameMenuItemKeyPressed

	private void saveMenuItemKeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_saveMenuItemKeyPressed
		gameFileChooser.startSaveChooser(MainWindow1.this);
	}// GEN-LAST:event_saveMenuItemKeyPressed

	private void loadMenuItemKeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_loadMenuItemKeyPressed
		if (!isSaved) //check if saved
		{
			SaveBeforeExitScreen.startSaveBeforeExitScreen(MainWindow1.this, "load");
		}
		else
		{
			gameFileChooser.startLoadChooser(MainWindow1.this);
		}
	}// GEN-LAST:event_loadMenuItemKeyPressed

	private void exitMenuItemKeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_exitMenuItemKeyPressed
		if (!isSaved) //check if saved
		{
			SaveBeforeExitScreen.startSaveBeforeExitScreen(MainWindow1.this, "exit");
		}
		else
		{
			ExitScreen.startExitScreen(MainWindow1.this);
		}
	}// GEN-LAST:event_exitMenuItemKeyPressed

	/*
	 * Change letter Button
	 */
	private void changeLetterActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_changeLetterActionPerformed
		// change letter button
		changeLetterFlag = true;
		changeLetter.setEnabled(false);
		addWordToBoard.setEnabled(false);
		setPlayStatusText("You have 3 more letter changes allowed");
		GameGui.initNumberOfChanges();
	}// GEN-LAST:event_changeLetterActionPerformed

	private void addWordToBoardActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_addWordToBoardActionPerformed
		// Add Word button
		addWordFlag = true;
		if (GameGui.getG().getMode() == 'a') {
			setPlayStatusText("Place only one letter and press Done");
		}
		changeLetter.setEnabled(false);
		addWordToBoard.setEnabled(false);
		GameGui.initUsedLetters();
	}// GEN-LAST:event_addWordToBoardActionPerformed

	private void helpMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_helpMenuItem1ActionPerformed
		helpPage.setVisible(true);
	}// GEN-LAST:event_helpMenuItem1ActionPerformed

	private void helpMenuItem1KeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_helpMenuItem1KeyPressed
		helpPage.setVisible(true);
	}// GEN-LAST:event_helpMenuItem1KeyPressed
    private void viewmenuKeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_helpMenuItem1KeyPressed
		viewComponent.setVisible(true);
	}// G

    private void viewmenuActionPerformed(java.awt.event.ActionEvent evt){
        viewComponent.setVisible(true);
}
        private void viewmenu2KeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_helpMenuItem1KeyPressed
		viewComponent2.setVisible(true);
	}// G

    private void viewmenu2ActionPerformed(java.awt.event.ActionEvent evt){
        viewComponent2.setVisible(true);
}
	private void changeLetterComponentAdded(java.awt.event.ContainerEvent evt) {// GEN-FIRST:event_changeLetterComponentAdded
		// TODO add your handling code here:
	}// GEN-LAST:event_changeLetterComponentAdded

	private void changeLetterComponentRemoved(java.awt.event.ContainerEvent evt) {// GEN-FIRST:event_changeLetterComponentRemoved
		// TODO add your handling code here:
	}// GEN-LAST:event_changeLetterComponentRemoved

	private void okHelpButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_okHelpButtonActionPerformed
		helpPage.dispose();
	}// GEN-LAST:event_okHelpButtonActionPerformed

	private void okBestBasicButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_okBestBasicButtonActionPerformed
		bestResultsPageBasic.dispose();
	}// GEN-LAST:event_okBestBasicButtonActionPerformed

	private void okBestAdvancedButtonActionPerformed(
			java.awt.event.ActionEvent evt) {// GEN-FIRST:event_okBestAdvancedButtonActionPerformed
		bestResultsPageAdvanced.dispose();
	}// GEN-LAST:event_okBestAdvancedButtonActionPerformed

	private void bestBasicActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_bestBasicActionPerformed
		bestResultsPageBasic.setVisible(true);
	}// GEN-LAST:event_bestBasicActionPerformed

	private void bestAdvancedActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_bestAdvancedActionPerformed
		bestResultsPageAdvanced.setVisible(true);
	}// GEN-LAST:event_bestAdvancedActionPerformed

      private void jBlueColorRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
           if(BlueLetter.isSelected()){
            redLetter.setSelected(false);
            BlueLetter.setSelected(true);
        }
        this.LetterColor = 0;
        gameBoard.loadLetters();
        gameBoard.repaint();
}

    private void jRedColorRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        if(redLetter.isSelected()){
            BlueLetter.setSelected(false);
            redLetter.setSelected(true);
        }
        this.LetterColor = 1;
        gameBoard.loadLetters();
        gameBoard.repaint();
}

    private void CustomTableAction(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

 

    private void OkViewActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        viewComponent.dispose();
    }
       private void RedTableHandler(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
           if(jRadioButton2.isSelected()){
         jRadioButton1.setSelected(false);
         jRadioButton3.setSelected(false);
         jRadioButton2.setSelected(true);
     }
            this.TableColor=1;
            gameBoard.repaint();
            
}
       private void BlueTableHandler(java.awt.event.ActionEvent evt){
            if(jRadioButton3.isSelected()){
         jRadioButton1.setSelected(false);
         jRadioButton2.setSelected(false);
         jRadioButton3.setSelected(true);
     }
            this.TableColor=2;
            gameBoard.repaint();
       }

    private void OkTableViewActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        viewComponent2.dispose();
}

    private void WhiteTableHandler(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
     if(jRadioButton1.isSelected()){
    	 jRadioButton2.setSelected(false);
         jRadioButton3.setSelected(false);
         jRadioButton1.setSelected(true);
     }
            this.TableColor=0;
            gameBoard.repaint();

    }
    private void AboutUsOkButtonEvent(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    	AboutUsDialog.dispose();
    }
	private void AboutUsActionPerformed(ActionEvent evt) {
		// TODO Auto-generated method stub
		AboutUsDialog.setVisible(true);
		
	}
	private void AboutUsKeyPressed(KeyEvent evt) {
		// TODO Auto-generated method stub
		AboutUsDialog.setVisible(true);
		
	}
	

	private void formWindowClosing(java.awt.event.WindowEvent evt) {// GEN-FIRST:event_formWindowClosing
		if (!isSaved) //check if saved
		{
			SaveBeforeExitScreen.startSaveBeforeExitScreen(MainWindow1.this, "exit");
		}
		else
		{
			ExitScreen.startExitScreen(MainWindow1.this);
		}
		
	}// GEN-LAST:event_formWindowClosing

	public void initGameWindow() {
//		Player p;
//		try {
//			p = GameGui.getG().getPlayerList().get(GameGui.getG().getTurnInd());
//		} catch (Exception e) {
//			p = player; // will be removed once the logic is complete
//		}
//		Board board = GameGui.getG().getBoard();
//		playStatus.setText("player " + p.getName() + " is playing");
		gameBoard.repaint();
	}

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String args[]) {
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				new MainWindow1().setVisible(true);
			}
		});
		return;
	}

	// Variables declaration - do not modify//GEN-BEGIN:variables
	private javax.swing.JMenuItem aboutUsMenuItem1;
	private javax.swing.JButton addWordToBoard;
	private javax.swing.JMenuItem bestAdvanced;
	private javax.swing.JScrollPane bestAdvancedjScrollPane;
	private javax.swing.JTextPane bestAdvancedjTextPane;
	private javax.swing.JMenuItem bestBasic;
	private javax.swing.JScrollPane bestBasicjScrollPane;
	private javax.swing.JTextPane bestBasicjTextPane;
	private javax.swing.JMenu bestResults;
	private javax.swing.JDialog bestResultsPageAdvanced;
	private javax.swing.JDialog bestResultsPageBasic;
	private javax.swing.JButton changeLetter;
	private javax.swing.JLabel currentPlayer;
	private javax.swing.JButton doneButton;
	private javax.swing.JMenuItem exitMenuItem;
	private DrawPanel gameBoard;
	private javax.swing.JMenu gameMenu;
	private javax.swing.JSeparator gameMenuSeparator;
	private javax.swing.JMenu helpMenu1;
	private javax.swing.JMenuItem helpMenuItem1;
	private javax.swing.JSeparator helpMenuSeparator1;
	private javax.swing.JDialog helpPage;
	private javax.swing.JScrollPane helpText1;
	private javax.swing.JScrollPane helpText2;
	private javax.swing.JTextPane helpjTextPane1;
	private javax.swing.JTextPane helpjTextPane2;
	private javax.swing.JMenuBar jMenuBar1;
	private javax.swing.JLabel letterSack;
	private javax.swing.JMenuItem loadMenuItem;
	private javax.swing.JMenuItem newGameMenuItem;
	private javax.swing.JButton okBestAdvancedButton;
	private javax.swing.JButton okBestBasicButton;
	private javax.swing.JButton okHelpButton;
	private static javax.swing.JTextPane playStatus;
	private javax.swing.JMenuItem saveMenuItem;
	private javax.swing.JTextPane scoreBoard;
	private javax.swing.JMenu viewMenu;
    private javax.swing.JDialog  viewComponent;
     private javax.swing.JDialog  viewComponent2;
    private javax.swing.JMenuItem viewMenuItem ;
    private javax.swing.JMenuItem viewMenuItem2 ;
    private javax.swing.JButton letterOk;
    private javax.swing.JLabel viewLetterT;
    private javax.swing.JLabel viewWindowT;
    private javax.swing.JRadioButton BlueLetter;
    private javax.swing.JRadioButton redLetter;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JRadioButton jRadioButton1;
    private javax.swing.JRadioButton jRadioButton2;
    private javax.swing.JRadioButton jRadioButton3;
    private javax.swing.JButton AboutUsOkButton;
    private javax.swing.JTextPane AboutUsTextPane1;
    private javax.swing.JScrollPane AboutUsjScrollPane1;
    private javax.swing.JDialog AboutUsDialog;
    // End of variables declaration


	// End of variables declaration//GEN-END:variables

	public class DrawPanel extends JPanel {

		public BufferedImage letters[];
		public BufferedImage exchangeLetters;
		int letterCoordsX[] = new int[7];
		int letterId[] = new int[7];
		public int letterMovedcoord = 80;
		public int[][] usedLettersId = new int[7][3]; // don't need this
		public int[] usedLetters = new int[7]; // don't need this too

		public DrawPanel() {
			loadLetters();
			this.addMouseListener(new java.awt.event.MouseAdapter() {
				public void mousePressed(java.awt.event.MouseEvent evt) {
					if (addWordFlag || changeLetterFlag) {
//						System.out.println("enter1");
						int i = letterListener(evt);
						if (i < 500 && addWordFlag) { // if place word on
														// board
							letterMovedcoord = i;
						} else if (i != 1000) { // if legal
							if ((i == 500) && (advancedLetterPlaced == false)){// if add word
								addLetterToBoard(evt.getPoint().x, evt
										.getPoint().y);
								if (GameGui.getG().getMode() == 'a') {
									advancedLetterPlaced = true;
								}
								
							}

							moveProgress = false; // end of operation
						}
					}
				}
			});
		}

		public void drawTable(Graphics g) {
			for (int i = 0; i < 15; i++) {
				for (int j = 0; j < 15; j++) {
					g.drawRect(j * 28, i * 28, 28, 28);
				}
			}
		}

		public int letterToNumber(char c) {
			char letters[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
					'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
					'v', 'w', 'x', 'y', 'z' };

			for (int i = 0; i < letters.length; i++)
				if (letters[i] == c)
					return i;

			return -1;
		}

		// draws the board from the logic
		public void drawBoard(Graphics g, Board b) {
			String path = "squarePicture.jpg";
			if(TableColor==1){
				path="squareRed.jpg";
			}
			if(TableColor==2){
				path="squarePicture4.jpg";
			}
			for (int i = 0; i < 15; i++)
				for (int j = 0; j < 15; j++) {
					g.drawRect(j * 28, i * 28, 28, 28);
					drawImage2(g,path,28,28,j*28,i*28);
					int id = letterToNumber(b.getLetter(i, j));
					if (id != -1)
						drawImage(letters[id], g, j * 28, i * 28);
				}
		}

		// draws player letters
		public void drawPlayerLetters(Graphics g, Player p) {
			for (int i = 0; i < p.getNumberOfLetters(); i++) {
				int id;
				letterCoordsX[i] = i * 40 + 80;
				try {
					id = letterToNumber(p.getLetter(i));
				} catch (Exception e) {
					id = -1;
				}
				g.drawRect(letterCoordsX[i], 440, 28, 28);
				if (id != -1) {
					drawImage(letters[id], g, letterCoordsX[i], 440);
				}
			}
		}

		// draws a picture of the exchange

		public void drawImage2(Graphics g,String filePath,int width,int height,int x, int y) {
//			String path = "resources/Letters/smily.jpg";80 80 380 425
			String path = filePath;
			Image img = null;
			InputStream input = resConfig.getImageStream(filePath);
			try{
				img = ImageIO.read(input);
			}
			catch(IOException e){}
			BufferedImage animated = resize(toBufferedImage(img), width, height);
			drawImage(animated, g,x, y);

		}

		// will not be needed
		public void drawLetterSet(Graphics g) {
			for (int i = 0; i < 7; i++) {
				g.drawRect(i * 40 + 80, 440, 28, 28);
				letterCoordsX[i] = i * 40 + 80;
			}
		}

		private void addLetterToBoard(int x, int y) {
			int i = (letterMovedcoord - 80) / 40;
			resultAdd = new resultAddLetter(i, x / 28, y / 28);
			
			
			/* usedLettersId[i][0] = letterId[i]; 
			 * usedLettersId[i][1] = x/28;
			 * usedLettersId[i][2] = y/28; if(usedLetters[i]==0){
			 * usedLetters[i]=1;
			 */
//			if (GameGui.getG().getMode() == 'b') {
//				GameGui.addLetterToBoardBasic(y / 28, x / 28, i);
//			}
//			else {
//				GameGui.addLetterToBoardAdvanced(y / 28, x / 28, i);
//			}
			GameGui.addLetterToBoardBasic(y / 28, x / 28, i);
			gameBoard.repaint();
		}

		/*
		 * This function returns the players actions on his turn The function
		 * returns a 2D int [7][3] if the player changed letters then on the
		 * place [6][0] will be written 500 and the letters id that have been
		 * changed will be written on [0][0],[1][0],[2][0] if the player put
		 * letters on the table the result is going to be that on the places
		 * [i][0] will be the id letter on [i][1] the x coordinate and on [i][2]
		 * the y coordinate
		 */
		public int[][] ResultPerTurn() { // don't need this
			return usedLettersId;
		}

		/*
		 * checks if we clicked in a valid square
		 */
		private boolean inSquare(int x, int y) {

			for (int i = 0; i < 7; i++) {
				if ((x >= letterCoordsX[i] && x <= letterCoordsX[i] + 28)
						&& (y >= 440 && y <= 440 + 28))
					return true;
			}
			return false;
		}

		/*
		 * checks if we are in the letter sack
		 */
		private boolean inLetterSack(int x, int y) {
			return (x >= 380 && x <= 380 + 90) && (y >= 425 && y <= 425 + 90);
		}

		public int letterListener(java.awt.event.MouseEvent evt) {
			Point point = evt.getPoint();
			int x = point.x;
			int y = point.y;
			if (inSquare(x, y)) { // if pressed the letter set
				moveProgress = true; // start the move
				if (changeLetterFlag) {
					// if we want to swap a letter
					moveProgress = false;
					resultSwap = new resultSwapLetter((x - 80) / 40); 
					GameGui.changeOneLetter(resultSwap.index);
					updateLetterSackBox();
					gameBoard.repaint();
					return 600;
				}
				return x;
			}
			// else if (changeLetterFlag && inLetterSack(evt.getX(),
			// evt.getY())) //if we swap letter
			// return 600;
			else {
				if ((addWordFlag == true) 
				 && (moveProgress == true) 
				 && (y > 0) && (y < 420) 
				 && (x > 0) && (x < 420)) { 
					return 500;
				}
				return 1000;
			}
		}
		
		
		public void paintComponent(Graphics g1) {

			super.paintComponent(g1); // JPanel draws background
			// drawTable(g1); //will be removed
			// drawLetterSet(g1);//will be removed
			// placeRandomLetters(g1);//will be removed

			drawBoard(g1, GameGui.getG().getBoard());
			Player p;
			try {
				p = GameGui.getG().getPlayerList().get(GameGui.getG().getTurnInd());
			} catch (Exception e) {
				p = player; // will be removed once the logic is complete
			}
			drawPlayerLetters(g1, p);
			drawImage2(g1,"smily.jpg",80,80,380,425);
		}

		// draws a given image
//		String path = "resources/Letters/smily.jpg";80 80 380 425
		public void drawImage(BufferedImage b, Graphics g, int x, int y) {
			Graphics2D g2 = (Graphics2D) g;
			g2.drawImage(b, null, x, y);

		}

		public void placeRandomLetters(Graphics g) {
			Random generator = new Random();
			for (int i = 0; i < 7; i++) {
				int r = generator.nextInt(26);
				letterId[i] = r;
				drawImage(letters[r], g, letterCoordsX[i], 440);
			}
		}

		public void loadLetters() {
			letters = new BufferedImage[27];
			InputStream input;
//			int style = GameGui.getG().getLetterMode();
			int style = LetterColor;
			for (int i = 1; i <= 27; i++) {
				String path;
				if (style == 0)
					input = lettersConfig.getImageStream(i + ".jpg");	
				else
					input = letter2Config.getImageStream(i + ".jpg");

				Image img = null;
				try{
					img = ImageIO.read(input);
				}
				catch(IOException e){}
				letters[i - 1] = resize(toBufferedImage(img), 28, 28);
			}
		}

		private BufferedImage resize(BufferedImage image, int width, int height) {
			BufferedImage resizedImage = new BufferedImage(width, height,
					BufferedImage.TYPE_INT_ARGB);
			Graphics2D g = resizedImage.createGraphics();
			g.drawImage(image, 0, 0, width, height, null);
			g.dispose();
			return resizedImage;
		}

		// This method returns true if the specified image has transparent
		// pixels
		public boolean hasAlpha(Image image) {
			// If buffered image, the color model is readily available
			if (image instanceof BufferedImage) {
				BufferedImage bimage = (BufferedImage) image;
				return bimage.getColorModel().hasAlpha();
			}

			// Use a pixel grabber to retrieve the image's color model;
			// grabbing a single pixel is usually sufficient
			PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
			try {
				pg.grabPixels();
			} catch (InterruptedException e) {
			}

			// Get the image's color model
			ColorModel cm = pg.getColorModel();
			return cm.hasAlpha();
		}

		public BufferedImage toBufferedImage(Image image) {
			if (image instanceof BufferedImage) {
				return (BufferedImage) image;
			}

			// This code ensures that all the pixels in the image are loaded
			image = new ImageIcon(image).getImage();

			// Determine if the image has transparent pixels; for this
			// method's
			// implementation, see e661 Determining If an Image Has
			// Transparent Pixels
			boolean hasAlpha = hasAlpha(image);

			// Create a buffered image with a format that's compatible with
			// the screen
			BufferedImage bimage = null;
			GraphicsEnvironment ge = GraphicsEnvironment
					.getLocalGraphicsEnvironment();
			try {
				// Determine the type of transparency of the new buffered
				// image
				int transparency = Transparency.OPAQUE;
				if (hasAlpha) {
					transparency = Transparency.BITMASK;
				}

				// Create the buffered image
				GraphicsDevice gs = ge.getDefaultScreenDevice();
				GraphicsConfiguration gc = gs.getDefaultConfiguration();
				bimage = gc.createCompatibleImage(image.getWidth(null), image
						.getHeight(null), transparency);
			} catch (HeadlessException e) {
				// The system does not have a screen
			}

			if (bimage == null) {
				// Create a buffered image using the default color model
				int type = BufferedImage.TYPE_INT_RGB;
				if (hasAlpha) {
					type = BufferedImage.TYPE_INT_ARGB;
				}
				bimage = new BufferedImage(image.getWidth(null), image
						.getHeight(null), type);
			}

			// Copy image to buffered image
			Graphics g = bimage.createGraphics();

			// Paint the image onto the buffered image
			g.drawImage(image, 0, 0, null);
			g.dispose();

			return bimage;
		}

	}

	// this class has data for the logic once a letter has been placed
	public class resultAddLetter {
		public int index; // the index of the letter in the maagar
		public int x, y; // the new coordinates of the word in the table

		public resultAddLetter(int index, int x, int y) {
			this.index = index;
			this.x = x;
			this.y = y;
		}

	}

	// this class has data for the logic once a letter is swaped
	public class resultSwapLetter {
		public int index; // the index of the letter i

		public resultSwapLetter(int index) {
			this.index = index;
		}
	}
	
	public static void setPlayStatusText(String text)
	{
		playStatus.setText(text);
	}
	
	
	/* This method updates the scoreBoard. Must be called after every turn. 
	 * */
	private void updateScoreBoard()
	{
		String allPlayers = "";
		//Added by eviatar to support the final screen
		String finish = (GameGui.getG().getLettersSet().getLetterSetSize() > 0) ? "Current" : "";
		int winner = 0;
		int winningScore = 0;
		for (int i = 0; i < GameGui.getG().getNumberOfPlayers(); i++) {
			int temp_score = GameGui.getG().getPlayerList().get(i).getScore();
			if (temp_score > winningScore)
			{
				winningScore = temp_score;
				winner = i;
			}
			allPlayers += GameGui.getG().getPlayerList().get(i).getName() + "\n"; 
			allPlayers += temp_score + " pts\n\n";
		}	
		String winMessage = finish + "Winner is:\n " + GameGui.getG().getPlayerList().get(winner).getName() +
		"\n\n With a score of:\n " + winningScore + " pts";
		allPlayers = winMessage + "\n\n" + allPlayers;
		scoreBoard.setText(allPlayers);
	}

	public static boolean isSaved() {
		return isSaved;
	}

	public static void setSaved(boolean isSaved) {
		MainWindow1.isSaved = isSaved;
	}
	
	public boolean showMessageDialog(String message, String title){
		int res = JOptionPane.showConfirmDialog(this, message,
                title, JOptionPane.YES_NO_OPTION,
                JOptionPane.YES_NO_CANCEL_OPTION);

		return res == 0;
	}
}
